package com.huanlis.provider.controller;

import com.huanlis.cloud.utils.R;
import com.huanlis.provider.domain.entity.TeacherEntity;
import com.huanlis.provider.service.TeacherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/async/provider")
public class HelloController {

    @Autowired
    private TeacherService teacherService;

    @GetMapping("/hello/test")
    public ResponseEntity<String> getTest(@RequestParam("id") Integer id) {
        log.info("收到请求：{}----{}", Thread.currentThread().getName(), id);
        try {
            Thread.sleep(1000 * 10);
        } catch (InterruptedException e) {
            log.error("收到请求：{}----{}: {}", Thread.currentThread().getName(), id, "延时错误");
            throw new RuntimeException(e);
        }
        log.info("返回结果：{}----{}", Thread.currentThread().getName(), id);
        return ResponseEntity.ok("id : " + id);
    }

    /**
     * 教师接口新增，模拟分支事务。当新增的教师为空或者大于30岁事会触发失败。
     *
     * @param teacherEntity 教师信息
     * @return com.huanlis.cloud.utils.R
     * @author lihuan
     * @since 2023/11/15 15:31
     */
    @PostMapping("/teacher/save")
    @Transactional(rollbackFor = Exception.class)
    public R saveTecher(@RequestBody TeacherEntity teacherEntity) {
        if (teacherEntity == null || teacherEntity.getAge() > 30) {
            throw new RuntimeException("fail");
        }
        teacherEntity.setCreateTime(LocalDateTime.now());
        teacherEntity.setUpdateTime(LocalDateTime.now());
        boolean save = teacherService.save(teacherEntity);
        return save ? R.success(teacherEntity.getId()) : R.fail();
    }

}
